﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;

namespace Department.admin.Content
{
    public partial class EditEduMaterial : System.Web.UI.Page
    {
        const int MAX_FILE_SIZE = AdminVariablesSingleton.MAX_FILE_SIZE;
        private string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect("/admin/Login.aspx");
            }
            if (Request.Params["ID"] == null) // Redirect user if the page is loaded without params
            {
                Response.Redirect("/admin/Content/ViewAllEduMaterials.aspx");
            }

            this.Page.Title = "Редакция на материал";

            AdminVariablesSingleton.configureCKEditor(ref newsTextBox);

            string heading = "";
            string text = "";
            bool isHidden = false;
            int discID = 0;
            string id = Request.Params["ID"];
            if (!Page.IsPostBack)
            {
                if (!(id == null))
                {
                    SqlConnection conn = new SqlConnection(strConnString);

                    try
                    {
                        conn.Open();

                        //Gets the news heading
                        string sqlHeading = "SELECT EducationMaterial.ID, EducationMaterial.Name, EducationMaterial.Description, EducationMaterial.EduMaterialTypeID, EducationMaterial.IsHidden, EducationMaterial.AcademicYear, EducationMaterial.DiscID, EduMaterialType.Name AS TypeName FROM EducationMaterial INNER JOIN EduMaterialType ON EducationMaterial.EduMaterialTypeID = EduMaterialType.ID WHERE EducationMaterial.ID = @ID";
                        SqlCommand comHeading = new SqlCommand(sqlHeading, conn);
                        comHeading.Parameters.AddWithValue("@ID", id);

                        SqlDataReader dataReader = comHeading.ExecuteReader();
                        DateTime academicYear = DateTime.Now;
                        while (dataReader.Read())
                        {
                            heading = dataReader.GetString(1);
                            text = dataReader.GetString(2);
                            isHidden = dataReader.GetBoolean(4);
                            academicYear = dataReader.GetDateTime(5);
                            discID = dataReader.GetInt32(6);
                        }
  
                        headingTextBox.Text = heading;
                        newsTextBox.Text = text;
                        TextBoxDate.Text = academicYear.ToShortDateString();
                        checkboxActive.Checked = !isHidden;
                        disciplineDropDownList.SelectedValue = discID.ToString();

                    }
                    catch (SqlException sqle)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
                    }
                    catch (Exception ex)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }

                }

            }

        }

        protected void buttonSubmit_Click(object sender, EventArgs e)
        {
            FileInfo[] arrayWithFileNames = new FileInfo[3];
            arrayWithFileNames = this.uploadFiles();
            string newsID = Request.Params["ID"];

            if (!newsID.Equals(""))
            {
                if (arrayWithFileNames[0] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[0], newsID);
                }
                if (arrayWithFileNames[1] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[1], newsID);
                }
                if (arrayWithFileNames[2] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[2], newsID);
                }
            }
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlUpdate = "UPDATE EducationMaterial SET Name=@Heading, Description=@Text, EduMaterialTypeID = @EduMat, IsHidden=@IsHidden, AcademicYear = @AcademicYear, DiscID=@DiscID WHERE ID = @ID";
                SqlCommand comUpdate = new SqlCommand(sqlUpdate, conn);
                string meca = headingTextBox.Text;
                comUpdate.Parameters.AddWithValue("@ID", Request.Params["ID"]);
                comUpdate.Parameters.AddWithValue("@Heading", headingTextBox.Text);
                comUpdate.Parameters.AddWithValue("@Text", newsTextBox.Text);
                comUpdate.Parameters.AddWithValue("@EduMat", EduMaterialDropDownList.SelectedValue);
                comUpdate.Parameters.AddWithValue("@AcademicYear", Convert.ToDateTime(TextBoxDate.Text));
                comUpdate.Parameters.AddWithValue("@IsHidden", !checkboxActive.Checked);
                comUpdate.Parameters.AddWithValue("@DiscID", disciplineDropDownList.SelectedValue);


                comUpdate.ExecuteNonQuery();
                Response.Redirect("~/admin/Content/ViewAllEduMaterials.aspx");
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
        }
        protected void toggleall_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkHeader = (CheckBox)sender;
            for (int i = 0; i < itemsView.Items.Count; i++)
            {
                CheckBox chk = (CheckBox)itemsView.Items[i].FindControl("CheckBoxIsMarked");
                chk.Checked = chkHeader.Checked;
            }
        }
        protected void markAllInactive_Click(object sender, CommandEventArgs e)
        {
            foreach (ListViewItem item in itemsView.Items)
            {
                CheckBox isSelectedCheckBox = (CheckBox)itemsView.Items[item.DisplayIndex].FindControl("CheckBoxIsMarked");
                if (isSelectedCheckBox.Checked)
                {
                    markAnItemInactive(((Label)item.FindControl("IDLabel")).Text);
                }
            }
            itemsView.DataBind();
        }
        protected void sortByHeading_Click(object sender, CommandEventArgs e)
        {


        }
        protected void markInactiveButton_Click(object sender, CommandEventArgs e)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = "DELETE FROM DocumentsToEduMaterials WHERE DocID = @DocID; DELETE FROM Documents WHERE ID = @DocID";
                SqlCommand insertDocument = new SqlCommand(sqlCommandText, conn);

                insertDocument.Parameters.AddWithValue("@DocID", e.CommandArgument);


                insertDocument.ExecuteNonQuery();

            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
            itemsView.DataBind();
        }
        private static void markAnItemInactive(string ID)
        {

        }
        protected FileInfo uploadFile(FileUpload fileControl)
        {
            if (fileControl.HasFile)
            {
                try
                {
                    if (fileControl.PostedFile.ContentLength < MAX_FILE_SIZE)
                    {
                        FileInfo fileInfo = new FileInfo();
                        string filename = Path.GetFileName(fileControl.FileName);
                        fileInfo.OriginalFileName = filename;

                        filename = DateTime.Now.ToUniversalTime().ToFileTimeUtc() + filename;
                        fileInfo.UniqueFileName = filename;

                        fileControl.SaveAs(Server.MapPath("~/files/uploadedFiles/") + filename);
                        fileInfo.FilePath = "~/files/uploadedFiles/" + filename;
                        return fileInfo;
                    }
                }
                catch (Exception ex)
                {
                    Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                }
            }
            return null;
        }
        protected FileInfo[] uploadFiles()
        {
            FileInfo[] arrayWithFileNames = new FileInfo[3];
            int arrayCounter = 0;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl);
            arrayCounter++;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl2);
            arrayCounter++;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl3);

            return arrayWithFileNames;
        }
        protected void insertDocumentForNews(FileInfo fileInfo, string newsID)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = "INSERT INTO Documents (Name, Description, Link, TypeID, FacDeptID) VALUES (@Name, @Description, @Link, (SELECT ID FROM Type WHERE Name = 'Documents'), dbo.uf_get_department_id())";
                SqlCommand insertDocument = new SqlCommand(sqlCommandText, conn);

                insertDocument.Parameters.AddWithValue("@Name", fileInfo.OriginalFileName);
                insertDocument.Parameters.AddWithValue("@Description", fileInfo.UniqueFileName);
                insertDocument.Parameters.AddWithValue("@Link", fileInfo.FilePath);

                insertDocument.ExecuteNonQuery();

                string sqlCommandText2 = "INSERT INTO DocumentsToEduMaterials (EduMaterialID, DocID) VALUES (@NewsID, @@Identity)";
                SqlCommand insertDocumentForNews = new SqlCommand(sqlCommandText2, conn);

                insertDocumentForNews.Parameters.AddWithValue("@NewsID", newsID);

                insertDocumentForNews.ExecuteNonQuery();
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }

        }

    }

}
